﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using pTools.cMethods;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace pTools.ChildWin
{
    public partial class selectPosition : Form
    {
        cMethods.DBHelper db;
        HttpAgreement http;
        string gxCode = "";
        public selectPosition(string types)
        {
            InitializeComponent();
            db = new cMethods.DBHelper();
            http = new HttpAgreement();
            gxCode = types;
        }
        private void selectPosition_Load(object sender, EventArgs e)
        {
            try
            {
                this.Text = "生产岗位选择";
                loadData();
                getPositionInfo();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void btnClose_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 加载岗位配置信息
        /// </summary>
        public void loadData()
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                var table = new DataTable();
                sb.Append("select cCode,cName from fun_CommonData_Info where isdel=0");
                sb.Append(" and cType='scgw' and status='Y' ");
                var cTable = db.getData(sb.ToString(), "");
                List<string> list = new List<string>();
                for (int i = 0; i < cTable.Rows.Count; i++)
                {
                    table.Columns.Add(cTable.Rows[i]["cCode"].ToString());
                    list.Add(cTable.Rows[i]["cName"].ToString() + "-" + cTable.Rows[i]["cCode"].ToString());
                }
                table.Columns.Add("usCode");
                table.Columns.Add("usName");
                sb.Clear();
                sb.Append("select g.*,u.userName from fun_Users_gangwei g ");
                sb.Append("inner join sys_users_info u on u.userCode=g.userCode");
                sb.Append(" where g.gxCode='"+gxCode+"'");
                var upTable = db.getData(sb.ToString(), "");
                List<string> ulist = new List<string>();
                for (int i = 0; i < upTable.Rows.Count; i++)
                {
                    string usCode = upTable.Rows[i]["userCode"].ToString();
                    string usName = upTable.Rows[i]["userName"].ToString();
                    var dr = upTable.Select("userCode='" + usCode + "'");
                    if (!ulist.Contains(usCode))
                    {
                        if (dr.Length > 0)
                        {
                            var row = table.NewRow();
                            row["usCode"] = usCode;
                            row["usName"] = usName;
                            foreach (DataRow r in dr)
                            {
                                row[r["gangwei"].ToString()] = "是";
                            }
                            table.Rows.Add(row);
                        }
                        ulist.Add(usCode);
                    }
                }
                this.dvList.DataSource = table;
                this.dvList.AutoGenerateColumns = false;
                for (int i = 0; i < table.Columns.Count; i++)
                {
                    if (dvList.Columns[i].Name == "usCode")
                    {
                        dvList.Columns[i].HeaderText = "员工工号";
                        continue;
                    }
                    else if (dvList.Columns[i].Name == "usName")
                    {
                        dvList.Columns[i].HeaderText = "员工姓名";
                        continue;
                    }
                    else
                    {
                        foreach (var str in list)
                        {
                            var arr = str.Split('-');
                            if (arr[1] == dvList.Columns[i].Name)
                            {
                                dvList.Columns[i].HeaderText = arr[0];
                            }
                        }
                    }
                 
                 
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }
        string msgs = "";
        List<JObject> pJsons = new List<JObject>();
        private void getPositionInfo()
        {
            Dictionary<string, string> pdic = new Dictionary<string, string>();
            pdic["gxCode"] = gxCode;

            var msg = http.PostJson("getPositionInfo", JsonConvert.SerializeObject(pdic));
            if (!string.IsNullOrWhiteSpace(msg))
            {
                var json = JsonConvert.DeserializeObject<JObject>(msg);
                if (bool.Parse(json["Result"].ToString()))
                {
                    pJsons = JsonConvert.DeserializeObject<List<JObject>>(json["Data"].ToString());
                    string info = "";
                    foreach (var j in pJsons)
                    {
                        info += j["contents"].ToString() + "；";
                    }
                  lbPosition.Text = info;
                }
            }
        }
        private void dvList_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                if (dvList.RowCount > 0)
                {
                    CommonMethods.Parameters["pCode"] = this.dvList.CurrentRow.Cells["pCode"].Value.ToString();
                }

                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        List<string> sValue = new List<string>();
        List<string> sText = new List<string>();
        private void dvList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                string chValue = "", chText="";
                DataGridViewCell cell = this.dvList.Rows[e.RowIndex].Cells[e.ColumnIndex];
                cell.ReadOnly=true;
                string value = dvList.CurrentRow.Cells["usCode"].Value.ToString();
                string cname = dvList.Columns[e.ColumnIndex].Name;
                string ctext = dvList.Columns[e.ColumnIndex].HeaderText;
                if (cell == null || cell.Value.ToString() == "" || cell.Value.ToString() == "0")
                {
                    return;
                }
                if (cname == "usCode" || cname == "usName")
                {
                    return;
                }
                var usCode= this.dvList.CurrentRow.Cells["usCode"].Value.ToString();
                var usName= this.dvList.CurrentRow.Cells["usName"].Value.ToString();
                chValue = string.Format("{0}-{1}", usCode, cname);
                chText = string.Format("{0}-{1}", usName, ctext);
                if (sValue.Count>0)
                {
                    for (int i = 0; i < sValue.Count; i++)
                    {
                        var arr = sValue[i].Split('-');
                        if (arr[0] == usCode)
                        {
                            sValue.Remove(sValue[i]);
                            sText.Remove(sText[i]);
                            break;
                        }
                       
                    }
           
                }
            
                    sValue.Add(chValue);
                    sText.Add(chText);
                    var ss = string.Join(",", sText.ToArray());
                    lbMsg.Text = ss;
            
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnConfirm_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                List<Dictionary<string, string>> plist = new List<Dictionary<string, string>>();
                string positionCode = "";
                string pCode = "";
                if (sValue.Count <1)
                {
                    MessageBox.Show("请先选择人员", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                if (pJsons.Count < 1)
                {
                    MessageBox.Show("没有预设的岗位信息", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                else
                {
                    #region 比对岗位是否复合要求
                    Dictionary<string, int> pDic = new Dictionary<string, int>();//选择的生产岗位数据
                    foreach (string j in sValue)
                    {
                        var arr = j.Split('-');
                        if (!pDic.ContainsKey(arr[1]))
                        {
                            pDic[arr[1]] = 1;
                        }
                        else
                        {
                            pDic[arr[1]] = pDic[arr[1]] + 1;
                        }
                  
                    }

                    #endregion
                    foreach (var j in pJsons)
                    {
                        var arr = j["pCodes"].ToString().TrimEnd(',').Split(',');//jizhang-2,xuetu-2  
                        var bp = new Dictionary<string, int>();//标准岗位信息
                      
                        foreach (string s in arr)
                        {
                            var sArr = s.Split('-');
                            if (!bp.ContainsKey(sArr[0]))
                            {
                                bp[sArr[0]] = int.Parse(sArr[1]);
                            }
                        }
                        #region 比对开始
                        if (arr.Length != pDic.Count)
                        {
                            continue;
                        }
                        bool isOk = true;
                        foreach (var item in bp)
                        {
                            if (pDic.ContainsKey(item.Key))
                            {
                                if (int.Parse(item.Value.ToString()) !=pDic[item.Key])
                                {
                                    isOk = false;
                                    break;
                                }
                            }
                            else
                            {
                                isOk = false;
                                break;
                            }
                        }
                        if (isOk)
                        {
                            pCode = j["pCode"].ToString();
                            break;
                        }
                        #endregion                   
                    }
                }
                if (string.IsNullOrWhiteSpace(pCode))
                {
                    MessageBox.Show("对不起，系统没有找到此岗位配置", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                CommonMethods.userPositionTitle = string.Join(",", sText.ToArray());
                CommonMethods.userPositionValue = string.Join(",", sValue.ToArray());
                CommonMethods.positionKey = pCode;
                if (string.IsNullOrWhiteSpace(positionCode))
                {
                    CommonMethods.userPositionCode = positionCode;
                }
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
